const app = getApp()
const mockData = require('../../utils/data.js')

Page({
  data: {
    history: []
  },
  
  onLoad() {
    this.loadHistory()
  },
  
  onShow() {
    this.loadHistory()
  },
  
  loadHistory() {
    const history = app.globalData.browsingHistory || []
    
    // 按日期分组
    const groupedHistory = {}
    history.forEach(item => {
      const date = item.date || '2019-06-17'
      if (!groupedHistory[date]) {
        groupedHistory[date] = []
      }
      
      const product = mockData.products.find(p => p.id === item.id) || mockData.products[0]
      groupedHistory[date].push({
        ...item,
        ...product
      })
    })
    
    // 转换为数组格式
    const historyList = Object.keys(groupedHistory).map(date => ({
      date,
      products: groupedHistory[date]
    })).sort((a, b) => new Date(b.date) - new Date(a.date))
    
    this.setData({
      history: historyList
    })
  },
  
  goToProductDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?id=${id}`
    })
  },
  
  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定要清空浏览记录吗？',
      success: (res) => {
        if (res.confirm) {
          app.globalData.browsingHistory = []
          wx.setStorageSync('browsingHistory', [])
          this.setData({
            history: []
          })
          wx.showToast({
            title: '已清空',
            icon: 'success'
          })
        }
      }
    })
  }
})


